package com.sgj.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.sgj.common.constant.AuthServerConstant;
import com.sgj.common.utils.HttpUtils;
import com.sgj.common.utils.R;
import com.sgj.common.vo.SocialUser;
import com.sgj.gulimall.auth.feign.MemberFeignService;
import com.sgj.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 社交登陆
 * @Author: Guoji Shen
 * @Date: 2021/9/7 11:16
 */
@Slf4j
@Controller
public class OAuthController {

    @Value("${gitee.client-id}")
    private String clientId;
    @Value("${gitee.redirect-uri}")
    private String redirectUri;
    @Value("${gitee.client-secret}")
    private String clientSecret;
    @Value("${gitee.grant-type}")
    private String grantType;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * gitee社交登录
     * @return
     */
    @GetMapping("/oauth/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {

        // 根据code换取accessToken
        Map<String, String> map = new HashMap<>();
        map.put("client_id", clientId);
        map.put("redirect_uri", redirectUri);
        map.put("client_secret", clientSecret);
        map.put("grant_type", grantType);
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());

        // 处理
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到了 accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            log.info("[OAuth2Controller][gitee] socialUser:{}", JSONObject.toJSONString(socialUser));

            // 知道当前是哪个社交用户
            // 当前用户如果是第一次进网站，自动为用户注册账号，以后此社交账号就对应指定的账号
            R oAuthLogin = memberFeignService.oAuthLogin(socialUser);
            if (oAuthLogin.getCode() == 0) {
                MemberRespVo data = oAuthLogin.getData("data", new TypeReference<MemberRespVo>() {});
                log.info("[OAuth2Controller][gitee] 登陆成功,用户信息为：{}", JSONObject.toJSONString(data));
                // 将用户数据存入session
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                // 登陆成功跳转回首页
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}